<?php
/**
 * Created by PhpStorm.
 * User: Yieong
 * Date: 14/11/24
 * Time: 上午9:48
 */

class UserController extends AdminBaseController {

	public function index(){
		$this->setTitle('用户列表', 'User list');
	
		$grid   = new PubGrid();
        $filter = new PubFilter();

        $userTypeOptions = UserService::userTypeOptions();
        $statusOptions   = UserService::statusOptions();
        $statusOptions = array('' => '所有') + $statusOptions;
        $filter->addFilter('search', 'input', PubFunc::t('用户名'), array('placeholder' => PubFunc::t('输入用户名或账号进行检索'), 'style' => 'width: 180px;'));
        $filter->addFilter('status', 'select', PubFunc::t('用户状态'), array('options' => $statusOptions, 'value' => key($statusOptions)));
        $params = $filter->get();
    	
        $page = $this->R('page', '1');
		$m = $this->R('m');
		$params['m'] = $m;
		$header = UserService::indexHeader();
		if(PubFunc::isAjax()){
			$result = UserService::indexData($params);
			$this->out = array(
					'count'     => $result['count'],
					'data'      => $result['data'],
					'result'    => true
			);
			$this->outType = 'json';
		}else{
			$order  = 'tbluser.AddTime';
			$url = PubFunc::ajaxUrl("?r=user/index", $params);
			$grid->addGrid($header, $url, array(
					'name'=>'数据',
					'order'=>array($order, 'asc'),
					'type'=>'user/index',
					'length'=>50,
					'page'=>$page
			));
	
			$this->out['filter'] = $filter->show();
			$this->out['grid'] = $grid->show();

		}
	}
	

    /**
     * 新增用户
     */
    public function add() { 	
        $form = new PubForm();
        $roleList = RoleaService::getRoleList();
        $roleList = array(''=>'请选择')+$roleList;
        $form->addItem('t1', 'title', PubFunc::t('基础信息'));
        $form->addItem('account', 'input', PubFunc::t('账号'));
        $form->addItem('username', 'input', PubFunc::t('用户名'));
        $form->addItem('password', 'pwd', PubFunc::t('密码'));
        $form->addItem('accall', 'radio', PubFunc::t('查看全服数据权限'), array('options' => array('1' => PubFunc::t('是'), '2' => PubFunc::t('否')), 'value' => 2));
            //->addItem('accadmin', 'radio', PubFunc::t('是否超级管理员'), array('options' => array('1' => PubFunc::t('是'), '2' => PubFunc::t('否')), 'value' => 2))
        $form->addItem('Status', 'radio', PubFunc::t('用户状态'), array('options' => array('1' => PubFunc::t('正常访问'), '2' => PubFunc::t('禁止访问')), 'value' => 1));
        $form->addItem('RoleID', 'select', PubFunc::t('角色'), array('options' => $roleList));
        $form->addOperation('提交', 'input', 'submit', 'btn btn-primary','sub');
        $form->addOperation('返回', 'a', PubFunc::buildUrl("/auth/?r=user/index"), 'btn btn-default');
        $form->setAction(PubFunc::buildBackUrl("/auth/?r=user/doAdd"));
        $form->setName('user');

        $this->out['form'] = $form->show();

        $this->setTitle('新增用户', 'Add User');
    }

    /**
     * 执行新增用户
     */
    public function doAdd(){
        $user = $this->R('user');
        $user['accadmin'] = 2; //只能添加非超级管理员
        $count = UserService::repeat(0, 'Account', $user['account']);
        if($count > 0){
    		$this->showMessage('账号已经存在');
    	}else{
    		$result = UserService::add($user);
    		$result = true;
    		if($result !== false){
    			$this->showMessage('新增成功', PubFunc::buildBackUrl("/auth/?r=user/index"));
    			//$this->redirect(PubFunc::buildUrl("/auth/?r=user/index"));
    		}else{
    			$this->showMessage('添加失败');
    		}
    	}
        
        
    }

    /**
     * 修改用户
     */
    public function edit(){
        $form = new PubForm();

        $id = $this->R('id');
        $user = UserService::getUserById($id, true);
        
        $modUserRoleMap = new ModUserRoleMap();
        $role = $modUserRoleMap->findByAttributes(array(
        		'UserID' => $user['UserID'],
        ))->attributes;

        $roleList = RoleaService::getRoleList();
        $page = $this->R('page');
        if(!empty($user)){
            $form->addItem('t1', 'title', PubFunc::t('基础信息'));
            $form->addItem('account', 'input', PubFunc::t('账号'), array('value' => $user['Account']));
            $form->addItem('username', 'input', PubFunc::t('用户名'), array('value' => $user['UserName']));
            $form->addItem('password', 'pwd', PubFunc::t('密码'), array('placeholder' => '为空则不修改密码'));
            $form->addItem('accall', 'radio', PubFunc::t('查看全服数据权限'), array('options' => array('1' => PubFunc::t('是'), '2' => PubFunc::t('否')), 'value' => $user['IsViewAll']));
                //->addItem('accadmin', 'radio', PubFunc::t('是否超级管理员'), array('options' => array('1' => PubFunc::t('是'), '2' => PubFunc::t('否')), 'value' => $user['IsAdmin']))
            $form->addItem('Status', 'radio', PubFunc::t('用户状态'), array('options' => array('1' => PubFunc::t('正常访问'), '2' => PubFunc::t('禁止访问')), 'value' => $user['Status']));
            if($user['IsAdmin'] == 2){
            	$form->addItem('RoleID', 'select', PubFunc::t('角色'), array('options' => $roleList,'value' => $role['RoleID']));
            }
            
            $form->addValue('user[id]', $id);
            $form->addOperation('提交', 'input', 'submit', 'btn btn-primary','sub');
            $form->addOperation('返回', 'a', PubFunc::buildBackUrl("/auth/?r=user/index"), 'btn btn-default');
            $form->setAction(PubFunc::buildBackUrl("/auth/?r=user/doEdit"));
            $form->setName('user');
            
            $this->out['form'] = $form->show();

            $this->setTitle('编辑用户', 'Edit User');
            
            $this->out['page'] = $page;
        }else{
            $this->showMessage('找不到用户');
        }
    }

    /**
     * 执行修改操作
     */
    public function doEdit(){
        $user = $this->R('user');
        if($user['id'] == 1){  //超级管理员
        	$user['accadmin'] = 1;
        }else{
        	$user['accadmin'] = 2; 
        }
        
        $count = UserService::repeat($user['id'], 'Account', $user['account']);
        if($count > 0){
        	$this->showMessage('账号已经存在');
        }else{
        	$result = UserService::edit($user);
        	$page = $this->R('page');
        	if($result !== false){
        		$this->showMessage('修改成功', PubFunc::buildBackUrl("/auth/?r=user/index"));
        	}else{
        		$this->showMessage('修改失败');
        	}
        }
        
    }

    public function delete(){
        $id = $this->R('id');
        $page = $this->R('page');
        if($this->isAuth !=1){  //isAuth为1则没有权限
        	if(UserService::delete($id)){
        		$this->showMessage('删除成功', PubFunc::buildBackUrl("/auth/?r=user/index"));
        	}else{
        		$this->showMessage('删除失败', PubFunc::buildBackUrl("/auth/?r=user/index"));
        	}
        }
        
    }

    /**
     * 获得游戏信息
     */
    public function game(){
        $id = $this->R('id');
        $user = UserService::getUserById($id);

        if(empty($user)){
            $this->showMessage(PubFunc::t('找不到该用户'));
        }else if($user['AccAdmin'] == '1'){
            $this->showMessage(PubFunc::t('超级管理员不需要授权游戏'));
        }else{
            $this->out['user']      = $user;
            $this->out['options']   = UserService::getGameList();
            $this->out['map']       = ModAuth::getUserGame($id);

            $this->setTitle('用户游戏设置', 'User Game Setting');
        }
    }


    public function grantGame(){
        $game       = $this->R('game');
        $platform   = $this->R('platform');
        $id         = $this->R('id');
        $allGame    = $this->R('all_game');

        $user = UserService::getUserById($id);

        if(empty($user)){
            $this->showMessage(PubFunc::t('找不到该用户'));
        }else if($user['AccAdmin'] == '1'){
            $this->showMessage(PubFunc::t('超级管理员不需要授权游戏'));
        }else{

            if(!empty($allGame)){
                UserService::updateByArr($id, array('HasAllGame' => 1));
                $result = UserGameMapService::delete($id);
            }else{
                UserService::updateByArr($id, array('HasAllGame' => 2));
                $result = UserGameMapService::add($id, $game, $platform);
            }

            if($result !== false){
                $this->showMessage('修改成功', '/auth/?r=user/game&id='.$id);
            }else{
                $this->showMessage('修改失败');
            }
        }
    }

    public function role(){
        $userId = $this->R('id');

        $user = UserService::getUserById($userId);

        if(empty($user)){
            $this->showMessage(PubFunc::t('找不到该用户'));
        }else if($user['AccAdmin'] == '1'){
            $this->showMessage(PubFunc::t('超级管理员不需要授权游戏'));
        }else{
            $this->out['user'] = $user;

            $this->out['userRole'] = UserRoleService::getRoleByUser($userId);

            $this->out['tree']   = RoleService::indexTree();
            $this->out['type']  = 'tree';

            // 设置标题
            $this->setTitle('角色列表', 'Role Info');
        }
    }

    public function saveRole(){
        $this->outType = 'json';

        $userId  = $this->R('user');
        $roleArr = $this->R('role');

        if(UserRoleService::addByUser($userId, $roleArr)){
            $this->out = array('state' => true);
        }else{
            $this->out = array('state' => false, 'msg' => '保存失败');
        }
    }

    public function grant(){
        $id = $this->R('id');
        $user = UserService::getUserById($id);

        if(empty($user)){
            $this->showMessage('角色不存在');
        }else{
            $this->out['user'] = $user;
            $this->setTitle('用户菜单编辑', 'Edit Role Menu');
        }
    }

    public function doGrant(){
        $user   = $this->R('user');
        $add    = $this->R('add');
        $delete = $this->R('delete');

        if(UserService::grantMenu($user, $add, $delete)){
            $this->out = 1;
        }else{
            $this->out = 2;
        }
        $this->outType = 'json';
    }
    
    public function channel(){
    	$id = PubRequest::R('id');
    	if(PubFunc::isAjax()){
    		$channel = PubRequest::R('channel');
    		UserService::batchDelete($id);
    		$result = UserService::doChannel($channel,$id);
    		$this->out = array(
    				'status' => 1,
    				'msg' => $result['msg'],
    				'data'    => ''
    		);
    		$this->outType = 'json';
    	}else{
    	
    		$modChannel = new ModChannel();
    		$list = $modChannel->selectAll();
    		
    		$data = array();
    		foreach ($list as $key=>$val){
    			$data[$val['game']][] = $val;
    		}

    	
    		$this->out['data'] = $data;
    		$this->out['id'] = $id;
    		
    		$url = PubFunc::buildUrl("/auth/?r=user/channel");
    		$this->out['url'] = $url;
    		
    		$channel = UserService::getUserChannel($id);
    		$channel_ids = array();
    		foreach ($channel as $key=>$val){
    			$channel_ids[] = $val['channel_id'];
    		}
    		$this->out['channel_ids'] = $channel_ids;
    		
    		$this->layout = '';    	
    	
    	}
    	
    	
    }

    // 获得角色的菜单列表
    public function getGrantMenu(){
        $userId = $this->R('user');

        $menuList = AccAuth::getMyMenu(AccAuth::me('UserID'));

        $result  = array();
        foreach($menuList as $v){
            $result[$v['ParentID']][$v['MenuID']] = $v;
        }

        $checked = MenuService::getUserMenu($userId);

        echo $this->echoTree($result, '0', 'MenuID', 'MenuName', $checked, true);
        $this->outType = 'ajax';
    }

    /**
     * 打印树级结构
     * @param $tree             树级数组
     * @param $start            开始节点
     * @param $id               ID字段名
     * @param $name             标题字段名
     * @param array $checked    默认选中的数组
     * @param bool $flag        是否返回
     * @return mixed|string|void
     */
    public function echoTree($tree, $start, $id, $name, $checked=array(), $flag=false) {
        $this->layout = '';

        $tree = array(
            'tree' => $tree,
            'start' => $start,
            'id' => $id,
            'name' => $name,
            'checked' => $checked
        );

        return $this->render('menu_tree', $tree, $flag);
    }
    
    /**
     * 修改密码
     */
    public function editSelf(){
    	$form = new PubForm();
    	$user = AccAuth::me();
    	$id = $user['UserID'];
    	$user = UserService::getUserById($id, true);
    
    	if(!empty($user)){
    		$form->addItem('t1', 'title', PubFunc::t('基础信息'));
    		$form->addItem('account', 'input', PubFunc::t('账号'), array('value' => $user['Account']));
    		$form->addItem('username', 'input', PubFunc::t('用户名'), array('value' => $user['UserName']));
    		$form->addItem('password', 'pwd', PubFunc::t('密码'), array('placeholder' => '为空则不修改密码'));
    		$form->addValue('user[id]', $id);
    		$form->addOperation('提交', 'input', 'submit', 'btn btn-primary','sub');
    		$form->setAction(PubFunc::buildBackUrl("/auth/?r=user/doEditSelf"));
    		$form->setName('user');
    		$this->out['form'] = $form->show();
    		$this->setTitle('修改密码', 'Edit User');
    	}else{
    		$this->showMessage('找不到用户');
    	}
    }
    
    /**
     * 执行修改操作
     */
    public function doEditSelf(){
    	$user = $this->R('user');   
    	$count = UserService::repeat($user['id'], 'Account', $user['account']);
    	if($count > 0){
    		$this->showMessage('账号已经存在');
    	}else{
    		$result = UserService::doEditSelf($user);
    		if($result !== false){
    			$this->showMessage('修改成功', PubFunc::buildBackUrl("/auth/?r=user/editSelf"));
    		}else{
    			$this->showMessage('修改失败');
    		}
    	}
    
    }

} 